#include "Client.hpp"
#include "General Utils.hpp"
#include <sstream>
using namespace std;

Client::Client()
{
	m_client = RakNetworkFactory::GetRakPeerInterface();
}

Client::~Client()
{
	if(m_client)
	{
		m_client->Shutdown(300);
		RakNetworkFactory::DestroyRakPeerInterface(m_client);
		m_client = 0;
	}

}

void Client::Send(const char* data)
{
	m_client->Send(data, sizeof(data), HIGH_PRIORITY, RELIABLE, 0, m_server, false);
}

bool Client::Connect()
{
	SocketDescriptor s(m_port + 1, 0);
	m_client->Startup(1, 0, &s, 1);
	m_client->Connect(m_IP.c_str(), m_port, 0, 0, 0);

	int tries = 0;
	while(true) // only 50 tries allowed
	{
		Packet *packet = m_client->Receive();

		if(packet == NULL)
			continue;

			if(packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED)
			{
				m_server = packet->systemAddress;
				m_client->DeallocatePacket(packet);
				return true;
			}

			if(packet->data[0] == ID_CONNECTED_SUCCESS)
			{
				m_server = packet->systemAddress;
				m_client->DeallocatePacket(packet);
				return true;
			}

			else if(packet->data[0] == ID_CONNECTION_ATTEMPT_FAILED)
			{
				m_client->DeallocatePacket(packet);
				return false;
			}
			m_server = packet->systemAddress;
			m_client->DeallocatePacket(packet);
		

		++tries;
	}
}

Packet* Client::GetIncomingPacket()
{
	return m_client->Receive();
}

void Client::KillPacket(Packet *packet)
{
	m_client->DeallocatePacket(packet);
}

void ParseData(int& pos, string& stored, unsigned char* data)
{
	while (data[pos] != '$') 
	{
		stored.push_back(data[pos]);
		++pos;
	}
	++pos;
}